﻿using SeeSharpTools.JY.DSP.Fundamental;
using Sunny.UI;
using System;

namespace SeeSharpTools.Demo
{
    public partial class FormAnalog : UIPage
    {
        public FormAnalog()
        {
            InitializeComponent();

            // 初始化下拉框
            uiComboBox.DataSource = new object[] { "正弦波", "方波", "三角波", "高斯调制正弦波", "Sinc信号", "周期Sinc信号" };
            uiComboBox.SelectedIndex = 0;
        }

        private void uiComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 设定默认采样率和采样数
            double sampleRate = 1000;
            int sampleCount = 1000;
            double[] signal = new double[sampleCount];

            // 根据选择生成信号
            switch (uiComboBox.SelectedIndex)
            {
                case 0:  // 正弦波
                    Generation.SineWave(ref signal, 1, 0, 50, sampleRate);
                    break;
                case 1: // 方波
                    Generation.SquareWave(ref signal, 1, 50, 50, sampleRate);
                    break;
                case 2: // 三角波
                    Generation.Triangle(ref signal, 1, 0, 50, sampleRate);
                    break;
                case 3: // 高斯调制正弦波
                    sampleRate = 10;
                    signal = Generation.Analog.GaussianModulatedSinePattern(sampleCount, out _, 1, 12.8, sampleRate);
                    break;
                case 4: // Sinc信号
                    sampleRate = 10;
                    signal = Generation.Analog.SincPattern(sampleCount, 1, 10, 1 / sampleRate);
                    break;
                case 5: // 周期Sinc信号
                    sampleRate = 10;
                    signal = Generation.Analog.PeriodicSincPattern(sampleCount, 1, 9, 10, sampleRate);
                    break;
                default:
                    signal = new double[sampleCount];
                    break;
            }

            // 在图表上绘制信号
            PlotSignal(signal, sampleRate);
        }

        // 生成信号的辅助函数
        private double[] GenerateSignal(Action generationAction)
        {
            double[] signal = new double[1000];
            generationAction.Invoke();
            return signal;
        }

        // 在图表上绘制信号和频谱
        private void PlotSignal(double[] signal, double sampleRate)
        {
            easyChartX1.Plot(signal, 0, 1 / sampleRate);
            double[] spectrum = new double[signal.Length / 2];
            Spectrum.PowerSpectrum(signal, sampleRate, ref spectrum, out double df, SpectrumUnits.dBV);
            easyChartX2.Plot(spectrum, 0, df);
        }
    }
}
